var amapFile = require('../../../../libs/amap-wx.130.js'); 
var gaode_key = require('../../../../libs/config');
var markersData = [];
Page({
  data: {
    markers: [],
    latitude: '',
    longitude: '',
    city: '',
    city_e: '',
    latitude_e: '',
    longitude_e: '',
    textData: {},
    gaode_type: 'car',
    polyline: [],
    includePoints: [],
    transits: [],
    mapEndObj: {},
    cost: '',
    distance: '',
    daohang: false,
    mapState: true,
    routeList: []  // 保留历史路线
  },
  
  makertap: function (e) {
    var id = e.markerId;
    var that = this;
    that.showMarkerInfo(markersData, id);
    that.changeMarkerColor(markersData, id);
  },
  
  onLoad: function () {
    this.getPoiData();
  },
  
  changeGaodeType(event) {
    this.setData({
      gaode_type: event.detail.gaode_type,
      mapState: false
    });
    if (!this.data.longitude_e) return;
    this.getRoute(this.data.mapEndObj, 'end');
  },
  
  handleCustomEvent: function (event) {
    const data = event.detail;
    this.setData({ mapEndObj: data.info });
    this.getRoute(data.info, data.inputType);
  },
  
  startNewRoute: function () {
    this.setData({
      city: '',
      city_e: '',
      latitude: '',
      longitude: '',
      latitude_e: '',
      longitude_e: '',
      polyline: [],
      cost: '',
      distance: '',
      daohang: false, // 不影响 addBox 显示
      mapEndObj: {},
      mapState: false,
      markers: [] // 清空地图上的标记点
    });
  
    this.getPoiData(); // 重新获取当前位置

  },

  getRoute: function (info, type) { 
    var that = this;
    if (type === 'start') {
      // 仅更新出发地，不影响 addBox
      const markersData = [{
        iconPath: "../../../../assets/plan/marker_checked.png",
        id: 0,
        latitude: info.location.split(',')[1],
        longitude: info.location.split(',')[0],
        width: 23,
        height: 33,
        name: info.name,
        address: info.district
      }];
      that.setData({
        city: info.name,
        latitude: info.location.split(',')[1],
        longitude: info.location.split(',')[0],
        polyline: [],
        markers: markersData,
        includePoints: [{ latitude: info.location.split(',')[1], longitude: info.location.split(',')[0] }]
      });
      return;
    } else {
      // 这里保证 addBox 只在 daohang 为 true 时存在
      that.setData({
        daohang: true,
        city_e: info.name,
        latitude_e: info.location.split(',')[1],
        longitude_e: info.location.split(',')[0]
      });
    }
  
    var key = gaode_key.Config.key;
    var myAmapFun = new amapFile.AMapWX({ key: key });
  
    const gaodeParams = {
      origin: `${this.data.longitude},${this.data.latitude}`,
      destination: `${this.data.longitude_e},${this.data.latitude_e}`,
      success: function (data) {
        var points = [];
        if (data.paths && data.paths[0] && data.paths[0].steps) {
          data.paths[0].steps.forEach(step => {
            step.polyline.split(';').forEach(point => {
              points.push({
                longitude: parseFloat(point.split(',')[0]),
                latitude: parseFloat(point.split(',')[1])
              });
            });
          });
        }
        
        const markersData = [{
          iconPath: "../../../../assets/plan/mapicon_navi_s.png",
          id: 0,
          latitude: that.data.latitude,
          longitude: that.data.longitude,
          width: 23,
          height: 33
        }, {
          iconPath: "../../../../assets/plan/mapicon_navi_e.png",
          // iconPath: "../../img/mapicon_navi_e.png",

          id: 1,
          latitude: that.data.latitude_e,
          longitude: that.data.longitude_e,
          width: 24,
          height: 34
        }]
        // 线的数据
        that.setData({
          polyline: [{
            points: points,
            color: "#0091ff",
            width: 6
          }],
          markers: markersData,
          includePoints: [{
            latitude: that.data.latitude,
            longitude: that.data.longitude
          }, {
            latitude: that.data.latitude_e,
            longitude: that.data.longitude_e
          }],
          mapState: true
          // 正在搜索
        });
        that.showMarkerInfo(markersData, 1);
        // 处理路线数据
        that.processRouteData(data, points);
      }
    };
  
    const setDistanceAndCost = (that, data) => {
      if (data.paths[0] && data.paths[0].distance) {
        that.setData({ distance: data.paths[0].distance + '米' });
      }
    };
    
    const setCostForCar = (that, data) => {
      if (data.taxi_cost) {
        that.setData({ cost: '打车约' + parseInt(data.taxi_cost) + '元' });
      }
    };
    
    
    if (this.data.gaode_type === 'car') {
      myAmapFun.getDrivingRoute(gaodeParams);
    } else if (this.data.gaode_type === 'walk') {
      myAmapFun.getWalkingRoute(gaodeParams);
    } else if (this.data.gaode_type === 'bus') {
      myAmapFun.getTransitRoute({
        origin: `${this.data.longitude},${this.data.latitude}`,
        destination: `${this.data.longitude_e},${this.data.latitude_e}`,
        city: '广州',
        success: function(data){
          console.log('公交信息', data.transits)
          if(data && data.transits){
            var transits = data.transits;
            for(var i = 0; i < transits.length; i++){
              var segments = transits[i].segments;
              transits[i].transport = [];
              for(var j = 0; j < segments.length; j++){
                if(segments[j].bus && segments[j].bus.buslines && segments[j].bus.buslines[0] && segments[j].bus.buslines[0].name){
                  var name = segments[j].bus.buslines[0].name
                  if(j!==0){
                    name = '--' + name;
                  }
                  transits[i].transport.push(name);
                }
              }
            }
          }
          that.setData({
            transits: transits,
            mapState: true
          });
            
        },
        fail: function(info){
          wx.showModal({
            title: info
          })
          console.log('出现问题', info)
        }
      })
    } else if (this.data.gaode_type === 'riding') {
      myAmapFun.getRidingRoute(gaodeParams);
    }
  },
  
// 统一处理不同出行方式的数据
processRouteData: function (data, points) {
  var that = this;
  let distance = data.paths[0]?.distance ? data.paths[0].distance + '米' : '';
  let cost = '';

  if (this.data.gaode_type === 'car' || this.data.gaode_type === 'riding') {
    if (data.taxi_cost) {
      cost = '打车约' + parseInt(data.taxi_cost) + '元';
    }
  } else if (this.data.gaode_type === 'walk') {
    if (data.paths[0]?.duration) {
      cost = parseInt(data.paths[0].duration / 60) + '分钟';
    }
  } else if (this.data.gaode_type === 'bus') {
    this.processBusRoute(data);
    return;
  }
  

  let updatedList = that.data.routeList || [];
  let existingIndex = updatedList.findIndex(route =>
    route.city === that.data.city && route.city_e === that.data.city_e
  );

  let newBox = {
    city: that.data.city,
    city_e: that.data.city_e,
    distance: distance,
    cost: cost,
  };

  if (existingIndex !== -1) {
    updatedList[existingIndex] = newBox;
  } else {
    updatedList.push(newBox);
  }

  that.setData({
    routeList: updatedList,
    polyline: [{ points: points, color: "#0091ff", width: 6 }],
    includePoints: [{ latitude: that.data.latitude, longitude: that.data.longitude }, { latitude: that.data.latitude_e, longitude: that.data.longitude_e }],
    mapState: true
  });
},

// 处理公交路线信息
processBusRoute: function (data) {
  var that = this;
  console.log('公交信息', data.transits);
  if (data && data.transits) {
    let transits = data.transits.map(transit => {
      let transport = [];
      transit.segments.forEach(segment => {
        if (segment.bus && segment.bus.buslines && segment.bus.buslines[0] && segment.bus.buslines[0].name) {
          let name = segment.bus.buslines[0].name;
          transport.push(name);
        }
      });
      return { ...transit, transport: transport.join('--') };
    });

    that.setData({
      transits: transits,
      mapState: true
    });
  }
},

  
// 地点搜索 如果搜索目的地搜索导航
getPoiData: function (keywords, searchType) {
  var that = this;
  let params = {
    iconPathSelected: '../../../../assets/plan/marker_checked.png', //如：..­/..­/img/marker_checked.png
    iconPath: '../../../../assets/plan/marker.png', //如：..­/..­/img/marker.png
    success: function (data) {
      console.log('当前位置', data)
      markersData = data.markers;
      // 搜索当前位置 附近poi
      console.log('搜索当前位置,清除目的地信息')
      that.setData({
        markers: markersData,
        latitude: markersData[0].latitude,
        longitude: markersData[0].longitude,
        city: markersData[0].name,
      });
      that.showMarkerInfo(markersData, 0);
    },
    fail: function (info) {
      wx.showModal({
        title: info.errMsg
      })
    }
  }
  if (keywords) {
    params.querykeywords = keywords;
  }
  var myAmapFun = new amapFile.AMapWX({
    key: gaode_key.Config.key
  });
  myAmapFun.getPoiAround(params)
},
showMarkerInfo: function (data, i) {
  var that = this;
  that.setData({
    textData: {
      name: data[i].name,
      desc: data[i].address
    }
  });
},
changeMarkerColor: function (data, i) {
  var that = this;
  var markers = [];
  for (var j = 0; j < data.length; j++) {
    if (j == i) {
      data[j].iconPath = "../../../../assets/plan/marker_checked.png"; //如：..­/..­/img/marker_checked.png
    } else {
      data[j].iconPath = "../../../../assets/plan/marker.png"; //如：..­/..­/img/marker.png
    }
    markers.push(data[j]);
  }
  that.setData({
    markers: markers
  });
}

});
